package com.pignest.hotel.system;

import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;

import com.pignest.hotel.beans.Duty;
import com.pignest.hotel.beans.DutyLog;
import com.pignest.hotel.beans.User;
import com.pignest.hotel.beans.global.ClientSession;
import com.pignest.hotel.definition.ChargeOpType;
import com.pignest.hotel.definition.PayMethod;
import com.pignest.hotel.service.DictionaryService;
import com.pignest.hotel.service.UserService;
import com.pignest.hotel.servlet.ImageServlet;
import com.pignest.hotel.spring.ContextHolder;
import com.pignest.hotel.spring.Services;

/** 
 * 系统配置, 常量或者字典表中设置的值
 *  */
public class Hotel {
	
	public static boolean TEST = false;
	private static User testUser;
	public static int self_living_preMoney=30000;//自助时所需要的押金单位分
	public static String showMoneySymbol="￥";

	//Session属性
	public static final String SESSION_LOGIN_USER_ID = "LoginUserID";
	public static final String SESSION_LOGIN_USER_REALNAME = "LoginRealName";
	public static final String SESSION_LOGIN_USER_PWD = "LoginUserPWD";
	public static final String SESSION_LOGIN_USER_ORGAN = "LoginUserOrgan";
	public static final String SESSION_LOGIN_LOG_ID = "LoginLogId";
	public static final String SESSION_USER_PRIVILEGE="UserPrivilige";
	//session监听器字符串名
	public static final String Hotel_SESSION_LISTENER = "HotelSessionListener";
	
	public static User getCurrentUser() {
		if (TEST) {
			if (testUser == null)
				testUser = Services.getUserService().getUserByWorkNo(Config.getSuperUserWorkNumber());
			if (testUser == null) {
				testUser = new User("测试用户", Config.getSuperUserWorkNumber(), "1", "123");
				testUser.setReserve(true);
			}
			return testUser;
		}
		ClientSession cs = AuthenticatorHolder.getClientSession();
		if (cs == null) {
			//from zk non-servlet thread
			Execution execution = Executions.getCurrent();
			if (execution != null) {
				HttpServletRequest request = (HttpServletRequest) execution.getNativeRequest();
				if (request != null) {
					cs = (ClientSession)request.getSession().getAttribute(Key.CLIENT_SESSION);
					if (cs != null) {
						AuthenticatorHolder.setClientSession(cs);
						return cs.getUser();
					}
				}
			}
			return null;
		}
		return cs.getUser();
	}
	
	/**
	 * 当前用户是否在值班
	 * */
	public static boolean onDuty() {
		Duty duty = getCurrentDuty();
		return duty != null && duty.getStatus() == Duty.STATUS_ON_DUTY;
	}
	
	@Deprecated
	public static void receive(int money, ChargeOpType purpose, PayMethod method) {
		receive(money, purpose, method, null);
	}
	
	/**
	 * 在当前值班人上累计金额, 收款时调用<br/>
	 * 注意: 由于修改了数据库, 在收款时需要加到共同的事务中
	 * xxxService.executeInTransaction, 或者在service中调用此方法
	 * */
	public static void receive(int money, ChargeOpType purpose, PayMethod method, String desc) {
		if (purpose == null || method == null || purpose == ChargeOpType.OnCharge && method == PayMethod.MEMBER_CARD)
			throw new IllegalArgumentException();
		Duty duty = getCurrentDuty();
		if (duty == null || duty.getStatus() != Duty.STATUS_ON_DUTY)
			throw new RuntimeException("not on duty");
		duty.receive(money, purpose, method);
		UserService service = Services.getUserService();
		service.update(duty);
		DutyLog log = new DutyLog(duty, money, purpose, method, desc);
		service.insert(log);
	}
	
	/**
	 * 当前值班
	 * */
	public static Duty getCurrentDuty() {
		User user = getCurrentUser();
		return Services.getUserService().getDuty(user);
	}
	
	public static boolean hasPermission(String permissions) {
		User user = getCurrentUser();
		return Permission.alow(permissions, user);
	}
	
	public static boolean hasPermission(Permission... permissions) {
		User user = getCurrentUser();
		for (Permission permission : permissions) {
			if (!permission.alow(user))
				return false;
		}
		return true;
	}
	
	public static String formatUrl(String url) {
		if (StringUtils.isEmpty(url) || url.charAt(0) != '/' || StringUtils.isEmpty(ContextHolder.getContextPath()))
			return url;
		return ContextHolder.getContextPath() + url;
	}
	
//	/** 房间照片存储路径 */
//	public static String getRoomPhotoPath() {
//		DictionaryService service = Services.getDictionaryService();
//		//XXX
//		return StringUtils.defaultIfEmpty(service.getValue(Key.ROOM_PHOTO_PATH), "E:\\hotel\\roomTypeImages\\");
//	}
	
	public static List<String> listFloors(){
		DictionaryService service = Services.getDictionaryService();
		return service.listValuesByPerfix(Key.FLOORS);
	}
	
	/**
	 * 获得网站地址
	 * @param aRequest
	 * @return
	 */
	public static String getSiteUrl(HttpServletRequest aRequest) {
		StringBuffer strURL = aRequest.getRequestURL();
		String URL = strURL.toString();
		String contPath = aRequest.getContextPath();
		int nIndex;
		if (contPath.length() > 0)
			nIndex = URL.indexOf(contPath);
		else
			nIndex = URL.lastIndexOf("/");
		if (nIndex == -1)
			nIndex = URL.length();
		URL = URL.substring(0, nIndex + contPath.length());
		return URL;
	}

	public static boolean login(HttpServletRequest request, HttpServletResponse response, 
			String workNo, String password, boolean remember) {
		try {
			UserService service = Services.getUserService();
			User user = service.getUserByWorkNo(workNo);
			if (user == null || !user.isEnable())
				return false;
			if (!checkPassword(user, password))
				return false;
			user.setLastLoginTime(user.getCurrentLoginTime());
			user.setCurrentLoginTime(new Date());
			HttpSession session = request.getSession(true);
			ClientSession cs = new ClientSession(user);
			cs.setClientIP(request.getRemoteHost());
			session.setAttribute(Key.CLIENT_SESSION, cs);
			AuthenticatorHolder.setClientSession(cs);
			L.log(L.Action.LOGIN);

			Cookie cookie = new Cookie(Key.WORK_NUMBER, workNo);
			cookie.setMaxAge(7 * 24 * 3600 * 1000);
			cookie.setPath(request.getContextPath());
			response.addCookie(cookie);
			if (remember) {
				Cookie cookie2 = new Cookie(Key.PASSWORD, password);
				cookie2.setMaxAge(365 * 24 * 3600 * 1000);
				cookie2.setPath(request.getContextPath());
				response.addCookie(cookie2);
			}
			session.setAttribute("px_preferred_locale", Locale.CHINA);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean checkPassword(User user, String input) {
		if (user == null || StringUtils.isEmpty(input))
			return false;
		String pass = user.getPassword();
		if (StringUtils.isEmpty(pass))		//可以加密后再判断
			pass = Config.getDefaultPassword();
		return pass.equals(input);
	}
	
	public static void logout(HttpServletRequest request, HttpServletResponse response) {
		L.log(L.Action.LOGOUT);
		ClientSession cs = AuthenticatorHolder.getClientSession();
		if (cs != null) {
			cs.logout();
			AuthenticatorHolder.setClientSession(null);
		}
		request.getSession(true).setAttribute(Key.CLIENT_SESSION, null);
		if (response != null) {
			response.addCookie(new Cookie(Key.PASSWORD, null));
		}
	}
	
	public static String[] getSelfServiceImages() {
		return ImageServlet.listImages();
	}
	
	public static String getUri(String uri) {
		String contextPath = ContextHolder.getContextPath();
		if (contextPath == null || contextPath.length() <= 1 || uri.length() < contextPath.length())
			return uri;
		return uri.substring(contextPath.length());
	}
}
